<template>
  <!-- 用户管理 -->
  <div class="search-user-table">
    <!-- <el-card> -->
    <div class="search-user-top">
      <div class="search-left">
        <el-input v-model="input" style="width: 240px" ref="inputRef" size="large" placeholder="用户姓名 / 登陆账号" clearable @blur="handleSearch" @keyup.enter="handleSearch" @clear="handleClear"/>
        <el-select v-model="stateValue" clearable ref="selectRef" placeholder="状态" size="large" style="width: 240px;height: 40px; " @clear="selectClear">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" @click="getTableData" :icon="Refresh" circle />
      </div>
      <div class="search-right">
        <el-button type="primary" @click="dialogFormVisible = true">+ 添加新用户</el-button>
      </div>
    </div>
    <div class="search-user-bottom">
      <el-table :data="tableData" v-loading="loading" style="width: 100%; height: 98%;" border stripe
        >
        <el-table-column type="index" label="序号" width="60" align="left" header-align="center"></el-table-column>
        <el-table-column prop="username" label="用户姓名" header-align="center"></el-table-column>
        <el-table-column prop="state" label="状态" header-align="center">
          <template #default="scope">
            <span v-if="scope.row.invalid * 1 === 2" style="color: green;" class="state-span">
              <el-icon color="green">
                <Check />
              </el-icon> 启用
            </span>
            <span v-else style="color: red;" class="state-span">
              <!-- <el-icon color="red">
                <CircleClose />
              </el-icon> 停用 -->
              <i class="iconfont icon-jinyong" style="color: red;"></i>停用
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="user_type" label="用户类型" header-align="center">
          <template #default="scope">
            <span v-if="scope.row.user_type * 1 === 10">
              <img src="../../public/images/admin_red_32.png" alt="">
              超级管理员
            </span>
            <span v-else>
              普通用户
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="登录账号" header-align="center"></el-table-column>
        <el-table-column prop="memo" label="备注" show-overflow-tooltip width="230" header-align="center">
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button-group>
              <el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
                <el-button type="primary" :icon="Edit" size="small" @click="EditRow(scope.row)" />
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="重置密码" placement="top">
                <el-button type="warning" :icon="RefreshRight" size="small" style="border-radius: 0;"
                  @click="resetPassword(scope.row)" />
              </el-tooltip>
              <!-- <span v-if="scope.row.state * 1 === 20"> -->
              <el-tooltip v-if="scope.row.invalid * 1 === 1" class="box-item" effect="dark" content="启用账号"
                placement="top">
                <el-button type="success" size="small" style="border-radius: 0;" :icon="CircleCheckFilled"
                  @click="InvalidData(scope.row)" />
              </el-tooltip>
              <!-- </span> -->
              <!-- <span v-else> -->
              <!-- 普通用户 -->
              <el-tooltip v-else class="box-item" effect="dark" content="停用账号" placement="top">
                <el-button type="info"  style="border-radius: 0;" size="small"
                class="iconfont icon-jinyong"
                  @click="InvalidData(scope.row)" />
              </el-tooltip>
              <!-- </span> -->
              <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row)" />
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- <div style="text-align: center; margin-top: 20px;"> -->
      <!-- </div> -->
    </div>
    <el-pagination background style="text-align: center;margin-top: 15px;height: 20px;" v-model:current-page="currentPage"
      v-model:page-size="pageSize" :page-sizes="[15, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <!-- </el-card> -->
  </div>
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" @close="resetForm">
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="姓名" prop="username" :label-width="formLabelWidth" required>
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户类型" prop="user_type" :label-width="formLabelWidth" required>
        <el-radio-group v-model="form.user_type">
          <el-radio :label="20">普通用户</el-radio>
          <el-radio :label="10">超级管理员</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="登陆账号" v-if="!isEdit" prop="account" :label-width="formLabelWidth" required>
        <el-input v-model="form.account" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" v-if="!isEdit" prop="pwd" :label-width="formLabelWidth" required>
        <el-input v-model="form.pwd" autocomplete="off" />
      </el-form-item>
      <el-form-item label="备注" prop="memo" :label-width="formLabelWidth">
        <el-input v-model="form.memo" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue'
import { TOKEN_KEY } from "@/enums/CacheEnum";
import { Check,RefreshRight,CircleCheckFilled,Delete,Edit,Message, CircleCloseFilled,Refresh} from '@element-plus/icons-vue';
import { ElMessageBox,ElMessage } from 'element-plus'
import UserManage from "@/api/userManage/userManage";
const formLabelWidth = '100px';
const hasToken = <string>localStorage.getItem(TOKEN_KEY);
const input = ref('')
const stateValue = ref('')
//下拉框内容
const options = [
  {
    value: 2,
    label: '启用',
  },
  {
    value: 1,
    label: '停用',
  },
]
//分页代码
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const handleSizeChange = (val: number) => {
  pageSize.value = val;
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};
//弹窗是否打开逻辑
const dialogFormVisible = ref(false);
//添加表单检验逻辑
const rules = {
  username: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  user_type: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  account: [
    { required: true, message: '请输入登陆账号', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
};

// 定义类型
interface createUserData {
  username?: string,
  user_type?: number | null,
  account?: string | null,
  memo?: string | null,
  pwd?: string | null,
  id?: string | null
};
//弹窗打开默认参数 
const form = ref<createUserData>({
  username: '',
  user_type: 20,
  account: '',
  memo: '',
  pwd: ''
});
const inputRef =ref(null);
const selectRef =ref(null);
const selectClear = ()=>{
  selectRef.value.blur(); // 让输入框失去焦点
  getTableData();
}
//重置表单内容
const formRef = ref()
const resetForm = () => {
  form.value = {
    username: '',
    user_type: 20,
    account: '',
    memo: '',
    pwd: ''

  };
  if (formRef.value) {
    formRef.value.clearValidate();
  }
  isEdit.value = false;
  currentUserId.value = null;
  dialogTitle.value = '添加用户'
};
//弹框头部默认名称
const dialogTitle = ref('添加用户');
//新增逻辑 
//弹框保存逻辑
const handleSave = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (isEdit.value && currentUserId.value) {
        // 编辑保存
        UserManage.updateUser(hasToken, currentUserId.value, form.value).then(res => {
          dialogFormVisible.value = false;
          ElMessage.success('用户编辑成功');
          resetForm();
          getTableData();
        }).catch(error => {
          console.error(error);
          ElMessage.error('用户编辑失败');
        });
      } else {
        //新增保存   
        UserManage.createUser(hasToken, form.value).then(res => {
          // console.log('res', res);
          dialogFormVisible.value = false;
          ElMessage.success('用户添加成功');
          resetForm();
          getTableData()
        })
      }
    } else {
      ElMessage.error('请填写完整的用户信息');
    }
  });

};

const isEdit = ref(false); // 用于区分是新增还是编辑
const currentUserId = ref<string | null>(null); // 当前编辑的用户ID

//编辑按钮点击逻辑
const EditRow = (row: any) => {
  dialogFormVisible.value = true;
  isEdit.value = true;
  dialogTitle.value = '用户详情';
  currentUserId.value = row.user_id.toString();
  const str = row.user_id.toString();
  UserManage.getUser(hasToken, str).then(res => {
    // console.log('res', res);
    //数据回填
    form.value = {
      username: res.data.username,
      user_type: res.data.user_type,
      account: res.data.account,
      memo: res.data.memo
    };
  }).catch(error => {
    console.error(error);
    ElMessage.error('获取用户信息失败');
  });
};

//停用开启账号
const InvalidData = (row: any) => {
  const isEnable = row.invalid * 1 === 1;
  // console.log('isEnable',isEnable);
  const confirmMessage = isEnable ? '确定要启用该账号嘛' : '确定要停用该账号嘛';
  const _invalid = isEnable ? '2' : '1';
  ElMessageBox.confirm(confirmMessage, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const str = row.user_id.toString();
    const obj = { invalid: _invalid, user_id: str }
    UserManage.setInvalid(hasToken, obj).then(res => {
      console.log('res', res);
      ElMessage.success('设置成功');
      getTableData();
    }).catch(error => {
      console.error(error);
      ElMessage.error('设置失败');
    });
  }).catch(() => {
    ElMessage.info('取消设置');
  });
}
//===================================================
//===================================================
//重置密码
const resetPassword = (row: any) => {
  ElMessageBox.confirm('确定要重置密码嘛', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const str = row.user_id.toString();

    UserManage.resetUser(hasToken, str).then(res => {
      // console.log('res', res);
      ElMessage.success('重置成功');
      getTableData()
    })
  }).catch(() => {
    ElMessage.info('取消重置');
  });
}
//删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const str = row.user_id.toString();

    UserManage.deleteUser(hasToken, str).then(res => {
      // console.log('res', res);
      ElMessage.success('删除成功');
      getTableData()
    })

  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
//表格默认
let tableData = ref([]);

//获取接口数据
// 定义类型
interface filterinterface {
  page?: string,
  page_size?: string | null,
  search?: string | null,
  invalid?: number | null
};

const filterData = ref<filterinterface>({
  page: currentPage.value.toString(),
  page_size: pageSize.value.toString(),
  search: input.value,
  invalid: Number(stateValue.value)
});
// 监听分页和搜索输入的变化
watch([currentPage, pageSize, stateValue], () => {
  filterData.value.page = currentPage.value.toString();
  filterData.value.page_size = pageSize.value.toString();
  // filterData.value.search = input.value;
  filterData.value.invalid = Number(stateValue.value)
  getTableData();
});
// 处理模糊搜索
const handleSearch = () => {
    filterData.value.search = input.value;
    getTableData();
};
//清空输入框
const handleClear = () => {
    filterData.value.search = '';
    inputRef.value.blur(); // 让输入框失去焦点
    getTableData();
};
const loading = ref(false);
//加载列表接口
const getTableData = () => {
  loading.value = true; // 开始加载
  UserManage.getUesrList(hasToken, filterData.value).then(res => {
    // console.log('res', res);
    tableData.value = res.data.list;
    total.value = res.data.total;
  }).finally(() => {
    loading.value = false; // 加载完成
  });
};
getTableData();

</script>
<style scoped>
.search-user-table {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}
.search-user-table /deep/ .is-leaf {
    background-color: var(--v-table-bg-color);
    color: var(--v-table-color);
    font-weight: bold;
}
/* .el-card {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
} */

.search-user-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.search-right .el-button {
  height: 40px;
}

.el-input,
.el-select {
  margin-right: 10px;
}

.search-user-bottom {
  height: calc(100% - 90px);
  /* overflow: auto; */
}

.el-pagination {
  float: right;
}

.el-table .el-button {
  margin: 0;
}
.state-span{
  display: flex;
  align-items: center;
}
.state-span .el-icon , .state-span i{
  margin-right: 5px;
}
.el-table img{
  width: 18px;
  height: 18px;
  margin-right: 5px;
  vertical-align: sub;
}
</style>